<!-- 弹窗 详情 -->
<script lang="tsx" setup>
import FileUpload from "@/components/file-system/file-upload.vue";
import type { FormDescChild } from "@/components/form-desc/form-desc.vue";
import {
	jeecgBootExExamCadetsListUsingPost,
	jeecgBootExExamOnekeyEnrollUsingPost,
  jeecgBootExExamEePageUsingPost
} from "@/genapi/exam";
import { useAsync } from "@/hooks/use-async";
import { ref } from "vue";
import {
	getEnumOptionsField,
	COURSE_TYPE_OPTIONS,
} from "@/config/enum-options";

import { injectState } from "../state";

defineOptions({ name: "DetailDialog" });

const img = import.meta.glob("./assets/*.png", {
	import: "default",
	eager: true,
});

const { page } = injectState()!;

const dialogRef = shallowRef<InstanceType<GlobalComponents["PromiseDialog"]>>();
const formDescRef = shallowRef<InstanceType<GlobalComponents["FormDesc"]>>();

const type = ref<"write" | "read">();

const beforeClose = async () => {
	if (type.value === "write") {
		await ElMessageBox.confirm("确认关闭？");
	}
};

const trigger = async (_type: "write" | "read" = "read", value = {} as any) => {
	type.value = _type;
	model.value = JSON.parse(JSON.stringify(value)) as any;

	await dialogRef.value?.open();
};

defineExpose({
	trigger,
});

const model = ref<(typeof page.records.value)[0]>({});
const value = ref("");

const file = computed({
	get() {
		if (model.value.fileId) {
			return [
				{
					id: model.value.fileId,
					name: model.value.fileName,
				},
			];
		}
	},
	set(value: any) {
		model.value.fileId = value?.[0]?.id;
	},
});

const title = computed(() => {
	if (type.value === "write") {
		return model.value.id ? "编辑" : "新建考试报名";
	} else {
		return `详情`;
	}
});

const { execute, isLoading } = useAsync(async () => {
	await formDescRef.value?.formRef?.validate();
	await ElMessageBox.confirm("确认提交？", "提示", {
		type: "warning",
	});

	await jeecgBootExExamOnekeyEnrollUsingPost({
		data: {
			...model.value,
		},
	});
	ElMessage.success("提交成功");
	page.execute();
	dialogRef.value?.complete();
});
const selectOptions = ref([{ label: "员工", value: "1" }]);

function getCurrentDate(): string {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, "0");
	const day = String(now.getDate()).padStart(2, "0");

	return `${year}-${month}-${day}`;
}
model.value.time = getCurrentDate();
const children: FormDescChild[] = [
	{
		label: "考试类型",
		prop: "category",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-select-v2
				v-model={model.value.category}
				options={COURSE_TYPE_OPTIONS}
				clearable
				class="w-240px!"
				placeholder="请选择类型"
        change={getCateforyData()}
			/>
		),
		descItem: () =>
			getEnumOptionsField(COURSE_TYPE_OPTIONS, "label", model.value.category) ??
			"-",
	},
];

interface Option {
	key: number;
	label: string;
	initial: string;
}

//点击培训类型的下拉框，从后端获取数据用来渲染培训名单
let categoryData = ref([])
let categoryData2 = ref([])
const getCateforyData = async () => {
  console.log(111)
  console.log(model.value.category)
  if(model.value.category){
    // jeecgBootTrSingupListUsingPost
    // jeecgBootTrSingupEnterprisePageUsingPost
    const res = await jeecgBootExExamEePageUsingPost({
		data: {
      "size": 15,
      "current": 1,
      "query": {
        "category": model.value.category,
        "examStatus": "3"
      }
    }
	});
  if (res && res.code === 200) {
    console.log(res.result)
    if(!res.result?.records){
      return categoryData.value = []
    }
		res.result?.records.forEach((item, index) => {
      console.log(item)
			categoryData.value.push({
				label: item.name,
				key: item.phone,
				initial: item.name,
			});
		});
    console.log(categoryData.value)
  }
  categoryData2.value = categoryData.value
  categoryData = ref([])
  }else{
    const res = await jeecgBootExExamEePageUsingPost({
		data: {
      "size": 15,
      "current": 1,
      "query": {
        "examStatus": "3"
      }
    }
	});
  if (res && res.code === 200) {
    console.log(res.result)
    if(!res.result?.records){
      return categoryData.value = []
    }
		res.result?.records.forEach((item, index) => {
      console.log(item)
			categoryData.value.push({
				label: item.name,
				key: item.phone,
				initial: item.name,
			});
		});
    console.log(categoryData.value)
  }
  categoryData2.value = categoryData.value
  categoryData = ref([])

  }
}

const generateData = async () => {
	const res = await jeecgBootExExamCadetsListUsingPost({
		data: {},
	});
	if (res && res.code === 200) {
		res.result?.forEach((item, index) => {
			data.value.push({
				label: item.name,
				key: item.phone,
				initial: item.name,
			});
		});
	}
	// const data: Option[] = [];
	// const states = [
	// 	"California",
	// 	"Illinois",
	// 	"Maryland",
	// 	"Texas",
	// 	"Florida",
	// 	"Colorado",
	// 	"Connecticut ",
	// ];
	// const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
	// states.forEach((city, index) => {
	// 	data.push({
	// 		label: city,
	// 		key: index,
	// 		initial: initials[index],
	// 	});
	// });
};

const data = ref<Option[]>([]);
const value1 = ref([]);

const filterMethod = (query, item) => {
	return item.initial.toLowerCase().includes(query.toLowerCase());
};

onMounted(() => {
	generateData();
});
</script>

<template>
	<PromiseDialog
		ref="dialogRef"
		:title="title"
		:before-close="beforeClose"
		w="700px!"
	>
		<el-scrollbar style="height: 508px">
			<FormDesc
				ref="formDescRef"
				m="t-24px x-30px"
				:type="type === 'read' ? 'desc' : 'form'"
				form-class="gap-x-20px"
				:model="model"
				:children="children"
				:column="3"
			/>
			<div class="trainingListBox">
				<div class="listBoxTitle">考试名单</div>
				<el-transfer
					v-model="model.phones"
					filterable
					:filter-method="filterMethod"
					filter-placeholder="请输入"
					:data="categoryData2"
					:titles="['人员名单', '考试人员']"
				/>
			</div>
		</el-scrollbar>
		<template v-if="type === 'write'" #footer>
			<el-button @click="dialogRef?.close()">取消</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>确定</el-button
			>
		</template>
	</PromiseDialog>
</template>

<style lang="scss" scoped>
.trainingListBox {
	width: 100%;
	padding: 0px 30px;
	.listBoxTitle {
		height: 50px;
		width: 100%;
		display: flex;
		align-items: center;
	}
}
</style>
